package main

import (
	"fmt"
	"linx/liface"
	"linx/lnet"
)

type HelloLinxRouter struct {
	lnet.BaseRouter
}

type PingRouter struct {
	lnet.BaseRouter
}

func (p *HelloLinxRouter) PreHandle(request liface.IRequest) {
	fmt.Println("Call HelloLinxRouter PreHandle ... ")
}

func (p *HelloLinxRouter) Handle(request liface.IRequest) {
	fmt.Println("Call HelloLinxRouter Handle ... ")
	fmt.Printf("req:%+v | data:%s\n", request, request.GetData())
	if err := request.GetConnection().SendMsg(10, []byte("HelloLinxRouter data msg")); err != nil {
		fmt.Println("Server sendMsg err:", err.Error())
	}
}

func (p *HelloLinxRouter) PostHandle(request liface.IRequest) {
	fmt.Println("Call HelloLinxRouter PostHandle ... ")
}

func (p *PingRouter) PreHandle(request liface.IRequest) {
	fmt.Println("Call PingRouter PreHandle ... ")
}

func (p *PingRouter) Handle(request liface.IRequest) {
	fmt.Println("Call PingRouter Handle ... ")
	fmt.Printf("req:%+v | data:%s\n", request, request.GetData())
	if err := request.GetConnection().SendMsg(20, []byte("PingRouter data msg")); err != nil {
		fmt.Println("Server sendMsg err:", err.Error())
	}
}

func (p *PingRouter) PostHandle(request liface.IRequest) {
	fmt.Println("Call PingRouter PostHandle ... ")
}

func DoConnectionBegin(connection liface.IConnection) {
	fmt.Println("=======> DoConnectionBegin is Called")
	if err := connection.SendMsg(202, []byte("DoConnection Begin")); err != nil {
		fmt.Println(err)
	}

	fmt.Println("Set conn Name, ")
	connection.SetProperty("Name", "yehongcheng")
	connection.SetProperty("Email", "yhcnet_e@163.com")
}

func DoConnectionEnd(connection liface.IConnection) {
	fmt.Println("=======> DoConnectionEnd is End")
	fmt.Printf("conn ID=%d is End\n", connection.GetConnID())

	if name, err := connection.GetProperty("Name"); err == nil {
		fmt.Println("Name=", name)
	}
	if email, err := connection.GetProperty("Email"); err == nil {
		fmt.Println("Email=", email)
	}
}

func main() {
	// 创建一个 Server 对象，使用 Linx 的api
	server := lnet.NewServer("{linx V0.6}")

	server.SetOnConnStart(DoConnectionBegin)
	server.SetOnConnStop(DoConnectionEnd)

	server.AddRouter(1, &HelloLinxRouter{})
	server.AddRouter(2, &PingRouter{})
	server.Serve()
}
